<script setup lang="ts">
import {
  reactive,
  ref,
  onMounted,
  onBeforeMount,
  computed,
  onUnmounted,
  watch,
  onActivated,
  onDeactivated,
  watchEffect
} from "vue";
import { FormInfo, InfoContainer } from "../components";
import { formInfo, tableProps } from "../components/interface";
import { AppTable } from "./Table";
import { columns_1, columns_2 } from "./Table/columns";
import axios from "axios";
import { any } from "vue-types";
import { bitUrlApi } from "../../../api/utils";

defineOptions({
  name: "AppHome"
});

// 使用reactive实现数据自动绑定到组件上
const formProps1: formInfo = reactive({
  title: undefined,
  btnNames: [undefined, undefined, undefined],
  btnDisabled: [false, false, false],
  formInfoList: [
    {
      id: 1,
      title: "机器类型",
      inputType: "0",
      placeholder: "梭织机",
      options: [
        {
          value: "梭织机",
          label: "梭织机"
        },
        {
          value: "整经机",
          label: "整经机"
        }
      ]
    },
    {
      id: 2,
      title: "布匹类型",
      inputType: "0",
      placeholder: "请选择类型",
      options: [
        {
          value: "平纹",
          label: "平纹"
        },
        {
          value: "斜纹",
          label: "斜纹"
        },
        {
          value: "缎纹",
          label: "缎纹"
        }
      ]
    }
  ]
});

const formProps2: formInfo = reactive({
  title: undefined,
  btnNames: [undefined, undefined, undefined],
  btnDisabled: [false, false, false],
  formInfoList: [
    {
      id: 1,
      title: "机器号",
      inputType: "0",
      placeholder: "请选择机器",
      options: [
        {
          value: "C9-328",
          label: "C9-328"
        }
      ]
    },
    {
      id: 2,
      title: "布匹等级",
      inputType: "0",
      placeholder: "请选择等级",
      options: [
        {
          value: "A",
          label: "A"
        },
        {
          value: "B",
          label: "B"
        },
        {
          value: "C",
          label: "C"
        }
      ]
    }
  ]
});

const propsTable: tableProps = reactive({
  tableData: [], // 表格数据
  columns: columns_1, // 表格样式
  pagination: { pageSize: 3, pageSizes: [3, 6, 9] }, // 分页配置
  onPagination: true // 是否启用分页
});

const propsTable2: tableProps = reactive({
  tableData: [], // 表格数据
  columns: columns_2, // 表格样式
  pagination: { pageSize: 3, pageSizes: [3, 6, 9] }, // 分页配置
  onPagination: true // 是否启用分页
});

const img_path_list = ref([]);

img_path_list.value = [
  "src/views/qualityInspection/home/asserts/default_img1.png",
  "src/views/qualityInspection/home/asserts/default_img2.png"
];
// propsTable.tableData = [
//   // {
//   //   error_type: "断纬",
//   //   date: "2024-07-13 09:15:34",
//   //   location: "(0，151)",
//   //   level: ""
//   // }
// ];

// 最好用英文命名
const count_duanjing = ref(0);
const count_duanwei = ref(0);
const count_podong = ref(0);
const count_sanbian = ref(0);
const count_wuzi = ref(0);

const count_guzhangtingji = ref(0);
const count_duanjingtingji = ref(0);
const count_duanweitingji = ref(0);
const count_jingjitingji = ref(0);
const count_shebeilixian = ref(0);
// 和后端通信完成 各个计数 以及 表格 的更新

const infoList = ref([]);
const infoList2 = ref([]);

// watch(() => infoList.value, () => {
//   console.log("检测到了变化")

//   // console.log(propsTable.tableData)
// })
const isFetching = ref(false);
const lockXiaci = ref(false);
const lockGuzhang = ref(false);

const FetchData = async () => {
  // count_duanjing.value++;
  // count_duanwei.value++;
  // count_podong.value++;
  // count_sanbian.value++;
  // count_wuzi.value++;
  // count_guzhangtingji.value++;
  // count_duanjingtingji.value++;
  // count_duanweitingji.value++;
  // count_jingjitingji.value++;
  // count_shebeilixian.value++;
  console.log("进入fetch函数");
  // if (isFetching.value) {
  //   return
  // }
  // // 上锁
  // isFetching.value = true
  // console.log("获取表格数据")

  if (lockXiaci.value) {
    return;
  } else {
    // 瑕疵数据获取加锁
    lockXiaci.value = true;
    try {
      let rst = await axios.post(bitUrlApi("/edgedb/list_data"), {
        table: "xiaci"
      });

      // // 更新 url
      // let urls = rst.data.data.topic;
      // xiaciDataLakeUrl.value = urls["xiaci"];
      // guzhangDataLakeUrl.value = urls["guzhang"];
      // console.log("data lake url: ", urls)

      // console.log(rst.data.data.data)
      infoList.value = rst.data.data.data;
      // console.log(infoList.value)
      propsTable.tableData = [];
      for (let i = 0; i < infoList.value.length; i++) {
        let item = infoList.value[i];
        // console.log(item)
        let error_type = item.type;
        let date = item.createTime;
        let x_y_w_h = JSON.parse(item.bbox);
        // let x_y_w_h = item.bbox

        propsTable.tableData.push({
          error_type: error_type,
          date: date,
          location: `(${(x_y_w_h[0] / 20).toFixed(1)}, ${(x_y_w_h[1] / 20).toFixed(1)})`
          // level: "等待查看"
        });
      }
      // console.log("table data: ", propsTable.tableData)
    } catch (err) {
      console.log("获取数据时出错：", err);
    }
    try {
      let rst = await axios.post(bitUrlApi("/edgedb/get_values_count"), {
        table: "xiaci"
      });
      let all_counts = rst.data.data.data;
      count_duanwei.value = all_counts["断纬"] ? all_counts["断纬"] : 0;
      count_duanjing.value = all_counts["断经"] ? all_counts["断经"] : 0;
      count_podong.value = all_counts["破洞"] ? all_counts["破洞"] : 0;
      count_wuzi.value = all_counts["污渍纱"] ? all_counts["污渍纱"] : 0;
      count_sanbian.value = all_counts["散边"] ? all_counts["散边"] : 0;
    } catch (err) {
      console.log("获取数据出错：", err);
    }
    // 释放瑕疵数据获取锁
    lockXiaci.value = false;
  }

  if (lockGuzhang.value) {
    return;
  } else {
    // 故障数据获取加锁
    lockGuzhang.value = true;
    try {
      let rst = await axios.post(bitUrlApi("/edgedb/list_data"), {
        table: "guzhang"
      });
      // console.log(rst.data.data.data)
      infoList2.value = rst.data.data.data;
      // console.log(infoList.value)
      propsTable2.tableData = [];
      for (let i = 0; i < infoList2.value.length; i++) {
        let item = infoList2.value[i];
        let error_type = item.type;
        let date = item.createTime;
        let machine_id = item.machineID;

        propsTable2.tableData.push({
          error_type: error_type,
          date: date,
          machineId: machine_id
        });
      }
      // console.log("table data: ", propsTable.tableData)
    } catch (err) {
      console.log("获取数据出错：", err);
    }

    try {
      let rst = await axios.post(bitUrlApi("/edgedb/get_values_count"), {
        table: "guzhang"
      });
      let all_counts = rst.data.data.data;
      // console.log("故障计数：", all_counts)
      count_guzhangtingji.value = all_counts["故障停机"]
        ? all_counts["故障停机"]
        : 0;
      count_duanjingtingji.value = all_counts["断经停机"]
        ? all_counts["断经停机"]
        : 0;
      count_duanweitingji.value = all_counts["断纬停机"]
        ? all_counts["断纬停机"]
        : 0;
      count_jingjitingji.value = all_counts["紧急停机"]
        ? all_counts["紧急停机"]
        : 0;
      count_shebeilixian.value = all_counts["设备离线"]
        ? all_counts["设备离线"]
        : 0;
    } catch (err) {
      console.log("获取数据出错：", err);
    }

    // 释放故障数据锁
    lockGuzhang.value = false;
  }

  // // 释放fetch锁
  // console.log("释放fetch锁")
  // isFetching.value = false
};

var timer = reactive(null);

function startTimer() {
  // 启动定时器，每秒调用一次 updateCurrentTime 方法
  if (timer === null) {
    timer = setInterval(FetchData, 1000);
  }
}
function stopTimer() {
  // 停止定时器
  if (timer !== null) {
    clearInterval(timer);
    timer = null;
  }
}

onMounted(() => {
  // startTimer();
  console.log("test url: ", bitUrlApi("/edgedb/list_data"));
  form1.value.infoChildren[0].value = "梭织机";
  form1.value.infoChildren[1].value = "平纹";
  form2.value.infoChildren[0].value = "C9-328";
  form2.value.infoChildren[1].value = "A";
  // console.log("onMounted:", form1.value.infoChildren[0].value)
  // 获取一次数据
  // FetchData()
  startTimer();
  // fetchDataLakeUrl()
});
// onBeforeMount(() => startTimer());
onUnmounted(() => {
  stopTimer();
});

onActivated(() => {
  startTimer();
  // fetchDataLakeUrl();
});

onDeactivated(() => {
  stopTimer();
});

// const xiaciDataLakeUrl = ref("");
// const guzhangDataLakeUrl = ref("");

// const fetchDataLakeUrl = async () => {
//   let rst = await axios.post(bitUrlApi("/edgedb/get_topic"));
//   let urls = rst.data.data.data;
//   xiaciDataLakeUrl.value = urls["xiaci"];
//   guzhangDataLakeUrl.value = urls["guzhang"];
//   console.log("data lake urls:", urls);
// };

let newWindow = null;

async function check_item(data) {
  // console.log(data);
  let index = data.row.id;
  // console.log("check line id: ", index)
  let uuidPred = infoList.value[index].uuidPred;
  console.log("check image uuid: ", uuidPred)
  // let uuidPred = "4d6c3b9e-7ab8-4ba8-8374-6f9d5989fc7e"
  // let topic_url = "hdfs://10.8.58.1:8020/kafka/test0905-camera-json"

  // 修改图片存取方式为后端数据库，废弃数据湖获取数据这条路
  // let topic_url = infoList.value[index].topic;
  // console.log("uuid: ", uuidPred);
  // console.log("topic_url: ", topic_url);

  // 如果窗口已经存在并且未关闭，则复用该窗口
  if (newWindow && !newWindow.closed) {
    newWindow.focus(); // 如果窗口已经存在，聚焦该窗口
    // 立即隐藏图片并显示加载提示
    var imgElement = newWindow.document.getElementById("image");
    var loadingElement = newWindow.document.getElementById("loading");
    loadingElement.style.display = "block";
    loadingElement.innerText = "加载中···";
    imgElement.style.display = "none";
  } else {
    // 如果窗口不存在或已关闭，创建一个新窗口
    newWindow = window.open("", "_blank", "width=800,height=600");

    // 插入初始的加载提示
    newWindow.document.write(`
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>图片窗口</title>
          <style>
              body {
                  display: flex;
                  justify-content: center;
                  align-items: center;
                  height: 100vh;
                  margin: 0;
                  background-color: #f0f0f0;
              }
              #loading {
                  font-size: 24px;
                  color: #333;
              }
              img {
                  max-width: 100%;
                  max-height: 100%;
                  object-fit: contain;
                  display: none; /* 图片默认隐藏 */
              }
          </style>
      </head>
      <body>
          <div id="loading">加载中···</div>
          <img id="image" src="" alt="Image" width=100%>
      </body>
      </html>
    `);
  }

  try {
    // 修改图片存取方式为后端数据库，废弃数据湖获取数据这条路
    // 发送请求，等待后端返回数据
    // let where_condition = `where uuid='${uuidPred}'`;
    // let whole_sql =
    //   "select filedata from delta.`" + topic_url + "`" + " " + where_condition;
    // console.log("sql: ", whole_sql);
    // let res = await axios.post("http://10.8.58.1:8400/sparkData/download/sql", {
    //   sql: whole_sql,
    //   type: "json"
    // });
    // console.log("results: ", res);
    // let imageUrl = `data:image/png;base64,${res.data[0].filedata}`;
    // console.log(imageUrl)

    let res = await axios.post(bitUrlApi("/edgedb/get_pred"), { table: "xiaci", uuid: uuidPred })
    // console.log("res:", res)
    let imageUrl = `data:image/png;base64,${res.data.data.data.image}`;
    // let imageUrl = `${res.data.data.image}`;

    // 获取新窗口中的 img 和 loading 元素
    var imgElement = newWindow.document.getElementById("image");
    var loadingElement = newWindow.document.getElementById("loading");

    // 设置图片的 src，直接显示图片，并隐藏加载提示
    imgElement.src = imageUrl;

    // 立即隐藏加载提示并显示图片
    loadingElement.style.display = "none";
    imgElement.style.display = "block";
  } catch (error) {
    // 如果请求失败，显示错误信息
    newWindow.document.getElementById("loading").innerText = "数据请求失败";
    console.error("Error fetching data:", error);
  }
}

// async function check_item(data) {
//   console.log(data)
//   let index = data.index
//   let uuidPred = infoList.value[index].uuidPred
//   console.log(uuidPred)
//   // return
//   // console.log(img_path_list.value[0])
//   // var imageUrl = img_path_list.value[data["index"]]; // 替换为你想要显示的图片URL
//   // console.log(imageUrl);
//   var newWindow = window.open("", "_blank", "width=800,height=600");
//   // console.log(data.row.error_type);
//   let res = await axios.post("http://10.8.58.1:8400/sparkData/query", {
//     path: "kafka/topic-quality-json"
//   });
//   console.log("res123", res);
//   let imageUrl = `${res.data.data.data[0].fileData}`;
//   // 在新窗口中插入图片
//   newWindow.document.write(`
//     <!DOCTYPE html>
//     <html lang="en">
//     <head>
//         <meta charset="UTF-8">
//         <meta name="viewport" content="width=device-width, initial-scale=1.0">
//         <title>图片窗口</title>
//         <style>
//             body {
//                 display: flex;
//                 justify-content: center;
//                 align-items: center;
//                 height: 100vh;
//                 margin: 0;
//                 background-color: #f0f0f0;
//             }
//             img {
//                 max-width: 100%;
//                 max-height: 100%;
//             }
//         </style>
//     </head>
//     <body>
//         <img src="${imageUrl}" alt="Image" width=700>
//     </body>
//     </html>
// `);
// }

function delete_item(data) {
  console.log(data);
  var index = data["index"];
  let uuid = infoList.value[index].uuid;
  axios
    .post(bitUrlApi("/edgedb/delete_data"), {
      uuid: uuid
    })
    .then(res => {
      // FetchData()
    })
    .catch(err => {
      alert(`请求失败，请稍后：${err}`);
    });
}

const form1 = ref();
const form2 = ref();

// const iframe_suozhi = computed(() => {
//   if (form1.value === undefined) {
//     return true;
//   } else {
//     if (form1.value.infoChildren[0].value == "梭织机") {
//       return true;
//     } else {
//       return false;
//     }
//   }
// });

const check_item2 = () => {};

const delete_item2 = () => { };


// Reactive state to toggle iframe sources
const iframeSuozhi = computed(() => {
  if (form1.value === undefined) {
    return true;
  } else {
    if (form1.value.infoChildren[0].value == "梭织机") {
      return true;
    } else {
      return false;
    }
  }
});

// Computed property for iframe source URL
const iframeSrc = computed(() => {
  return iframeSuozhi.value
    ? "http://10.8.58.39:8089/loom/internalFrame.html"
    : "http://10.8.58.39:8089/warping/internalFrame.html";
});

// Fullscreen mode trigger function
const goFullscreen = () => {
  const iframe = document.querySelector('iframe'); // Select the iframe element
  if (iframe) {
    const requestFullscreen = iframe.requestFullscreen || iframe.mozRequestFullScreen || iframe.webkitRequestFullscreen || iframe.msRequestFullscreen;

    if (requestFullscreen) {
      requestFullscreen.call(iframe).catch((err) => {
        console.error(`Error attempting to enable full-screen mode: ${err.message}`);
        // Optionally, provide user feedback here
      });
    }
  }
};

</script>

<template>
  <div>
    <el-row class="app-home-head" justify="space-between">
      <el-col :span="6">
        <FormInfo
          ref="form1"
          :title="formProps1.title"
          :btnNames="formProps1.btnNames"
          :btnDisabled="formProps1.btnDisabled"
          :formInfoList="formProps1.formInfoList"
        >
          <template #afc1>
            <div class="afc1-title">瑕疵数量</div>
            <div class="afc1-content">
              <div class="afc1-item">
                <span>断经</span>
                <div>{{ count_duanjing }}</div>
              </div>
              <div class="afc1-item">
                <span>断纬</span>
                <div>{{ count_duanwei }}</div>
              </div>
              <div class="afc1-item">
                <span>破洞</span>
                <div>{{ count_podong }}</div>
              </div>
              <div class="afc1-item">
                <span>散边</span>
                <div>{{ count_sanbian }}</div>
              </div>
              <div class="afc1-item">
                <span>污渍纱</span>
                <div>{{ count_wuzi }}</div>
              </div>
            </div>
          </template>
        </FormInfo>
      </el-col>
      <el-col :span="11">
        <InfoContainer class="">
          <div class="iframe-container">
            <iframe
              width="100%"
              height="375px"
              :src="iframeSrc"
              style="border: none;"
            />
            <button @click="goFullscreen" class="fullscreen-button">
            <span class="fullscreen-icon">⛶</span>
      </button>
          </div>
        </InfoContainer>
      </el-col>
      <el-col :span="6">
        <FormInfo
          ref="form2"
          :title="formProps2.title"
          :btnNames="formProps2.btnNames"
          :btnDisabled="formProps2.btnDisabled"
          :formInfoList="formProps2.formInfoList"
        >
          <template #afc1>
            <div class="afc1-title">故障数量</div>
            <div class="afc1-content">
              <div class="afc1-item">
                <span>故障停机</span>
                <div>{{ count_guzhangtingji }}</div>
              </div>
              <div class="afc1-item">
                <span>断经停机</span>
                <div>{{ count_duanjingtingji }}</div>
              </div>
              <div class="afc1-item">
                <span>断纬停机</span>
                <div>{{ count_duanweitingji }}</div>
              </div>
              <div class="afc1-item">
                <span>紧急停机</span>
                <div>{{ count_jingjitingji }}</div>
              </div>
              <div class="afc1-item">
                <span>设备离线</span>
                <div>{{ count_shebeilixian }}</div>
              </div>
            </div>
          </template>
        </FormInfo>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <InfoContainer class="app-home-footer">
          <AppTable
            class="add-table"
            :table-data="propsTable.tableData"
            :columns="propsTable.columns"
            :pagination="propsTable.pagination"
            :on-pagination="propsTable.onPagination"
            @clickbtn1="check_item"
            @clickbtn2="delete_item"
          />
        </InfoContainer>
      </el-col>
      <!-- <el-col :span="1"></el-col> -->
      <el-col :span="12">
        <InfoContainer class="app-home-footer">
          <AppTable
            class="add-table"
            :table-data="propsTable2.tableData"
            :columns="propsTable2.columns"
            :pagination="propsTable2.pagination"
            :on-pagination="propsTable2.onPagination"
            @clickbtn1="check_item2"
            @clickbtn2="delete_item2"
          />
        </InfoContainer>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.app-home-head {
  height: 57vh;

  .afc1-title {
    font-weight: bold;
  }

  .afc1-content {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .afc1-item {
      flex: 0 0 48%;

      span {
        color: rgb(176 177 179);
      }
    }
  }
}

.app-home-footer {
  margin-top: 2vh;
}

.iframe-container {
  position: relative;
  width: 100%;
  height: 375px;
  background-color: rgba(255, 255, 255, 0.0);
}

.fullscreen-button {
  position: absolute;
  bottom: 10px; /* Position from the bottom */
  right: 20px; /* Position from the right */
  // padding: 10px;
  padding-left: 10px;
  padding-right: 10px;
  // padding-top: 3px;
  // padding-bottom: 3px;
  background-color: rgba(255, 255, 255, 0.0); /* Semi-transparent background */
  border: none;
  border-radius: 25%; /* Circular button */
  cursor: pointer;
  font-size: 30px; /* Icon size */
  color: #000000; /* Icon color */
  transition: background-color 0.3s; /* Smooth hover effect */
}


.fullscreen-button:hover {
  background-color: rgba(255, 255, 255, 0.5); /* Change on hover */
  color: rgb(0, 0, 0);
}

.fullscreen-icon {
  line-height: 1; /* Adjust vertical alignment */
}
</style>
